//
//  HMUserAccount.swift
//  Weibo
//
//  Created by 黄亦寒 on 2016/9/22.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
//存储和读取的沙盒路径
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("UesrAccount.archiver")
//用户账号模型
class HMUserAccount: NSObject,NSCoding{

    //令牌
    var access_token:String?
    
    //令牌的过期时间
    var expires_in:TimeInterval = 0 {
        didSet {
            //过期时间 = 当前时间 + 过去秒数
            expiresDate = Date().addingTimeInterval(expires_in)
        }
    }
    //过期时间对象
    var expiresDate:Date?
    
    //授权用户的uid
    var uid:Int64 = 0
    
    //名字
    var name:String?
    
    //头像
    var avatar_large:String?
    
    //字典转模型
    init(dic:[String:Any]) {
        super.init()
        setValuesForKeys(dic)
    }
    
    //防止崩溃
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    //归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as! String?
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as! Date?
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as! String?
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as! String?
        
    }
    
    //保存当前用户对象
    func saveUserAccount() -> Void {
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
        
    }
    
    //从指定沙盒路径加载用户对象
    class func loadUserAccount() -> HMUserAccount? {
       return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? HMUserAccount
    }
}
